package com.dcivision.framework;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;


public class HTTPUtility {

  public static final String CONTENT_TYPE="application/octet-stream";
  
  
  public static String getContentType(String documentName){
    return getContentType(documentName,null);
  }
  
  /**
   * get contentType for HttpServletResponse
   * @param documentName
   * @param referenceType
   * @return
   */
  public static String getContentType(String documentName,String referenceType){
    if(documentName==null || "".equals(documentName.trim())){
      return CONTENT_TYPE;
    }
    
    String type = URLConnection.guessContentTypeFromName(documentName);
    if(type==null && referenceType!=null && !"".equals(referenceType.trim())){
      type=referenceType;
    }
    if(type==null){
      type=CONTENT_TYPE;
    }
    return type;
  }
  
  /**
   * get contentType for HttpServletResponse
   * @param is 
   * @param referenceType
   * @return
   */
  public static String getContentType(InputStream is,String referenceType) throws IOException{
    if(is==null){
      return CONTENT_TYPE;
    }
    
    String type = URLConnection.guessContentTypeFromStream(is);
    if(type==null && referenceType!=null && !"".equals(referenceType.trim())){
      type=referenceType;
    }
    if(type==null){
      type=CONTENT_TYPE;
    }
    return type;
  }
}
